<template>
  <div>
    <el-card class="box-card">
      <div class="boxMain">
        <el-button style="margin-bottom: 20px;margin-right: 20px" type="primary" icon="el-icon-bottom" round @click="downloadTemplate()">模板下载</el-button>
        <el-button type="success" round class="el-icon-upload2" @click="dialogVisibleExcel = true">批量导入</el-button>
      </div>
      <div style="margin-right: 27%">
        操作说明：请点击"模板下载"按钮获取模板文件，在模板文件中录药品数据后点击"上传文件"按钮上传模板文件。
      </div>
    </el-card>
    <div style="padding-top: 10px;background-color: #ffffff">
      <!-- 表单 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="display: flex;margin-left: 2%">
        <el-form-item label="">
          <el-input v-model="page.queryString" placeholder="药名  /  分类 / 成分"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="el-icon-circle-plus-outline" @click="handleAddBtn">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-refresh-left" @click="refreshUn">清空</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" :pagination="false" border style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50%" align="center" />
        <el-table-column prop="id" label="编号" width="200" align="center">
          <template v-slot="{ row }">
            <el-tag type="danger">{{row.id}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="药名" width="180" align="center"></el-table-column>
        <el-table-column prop="category" label="药物分类" width="180" align="center"></el-table-column>
        <el-table-column prop="imageUrl" label="图片" width="180" align="center">
          <template v-slot="{ row }">
            <img :src="row.imageUrl" width="100px" height="70px">
          </template>
        </el-table-column>
        <el-table-column prop="ingredient" label="成分" width="300" align="center"></el-table-column>
        <el-table-column prop="indication" label="适应症" width="300" align="center"></el-table-column>
        <el-table-column prop="usageDosage" label="用法用量" width="700" align="center"></el-table-column>
        <el-table-column prop="taboo" label="禁忌" width="700" align="center"></el-table-column>
        <el-table-column prop="adverseReaction" label="不良反应" width="500" align="center"></el-table-column>
        <el-table-column prop="lookOut" label="注意事项" width="700" align="center"></el-table-column>
        <el-table-column prop="drugInteraction" label="药物相互作用" width="300" align="center"></el-table-column>
        <el-table-column prop="atcCode" label="ATC编码" width="140" align="center"></el-table-column>
        <el-table-column prop="specification" label="规格/包装" width="140" align="center"></el-table-column>
        <el-table-column el-table-column fixed="right" label="操作" width="270" align="center">
          <template v-slot="scope">
            <el-button type="warning" size="mini" class="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              icon="el-icon-info"
              icon-color="red"
              @confirm="deleteItem(scope.row)"
              style="margin-left: 5px;white-space: nowrap"
            >
              <el-button :disabled="!deleteButton" slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div style="text-align: right;padding: 10px 20px;" >
        <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          :current-page="page.page"
          :page-sizes="[5, 10, 15, 25, 30]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total" />
      </div>
      <!-- 编辑标签弹层 -->
      <div class="add-form">
        <el-dialog title="编辑信息" :visible.sync="dialogFormVisible4Edit" :modal="false">
          <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" status-icon label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="药名" prop="name">
                  <el-input v-model="formData.name"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成分" prop="ingredient">
                  <el-input v-model="formData.ingredient"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="适应症" prop="indication">
                  <el-input v-model="formData.indication"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格/包装" prop="specification">
                  <el-input v-model="formData.specification"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="分类" prop="category">
                  <el-select v-model="formData.category" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                    <!-- 注意：el-option 设置了 value 属性 -->
                    <el-option v-for="categoryOption in categoryOptions" :key="categoryOption" :label="categoryOption" :value="categoryOption"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <div class="custom-upload-container">
                  <div class="upload-title">图片上传</div>
                  <el-upload
                    class="avatar-uploader"
                    :action="baseUrl + '/image/userImage'"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :file-list="fileList"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="药物相互作用" prop="drugInteraction">
                  <el-input v-model="formData.drugInteraction"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="ATC编码" prop="atcCode">
                  <el-input v-model="formData.atcCode"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="禁忌" prop="taboo">
                  <el-input v-model="formData.taboo" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="用法用量" prop="usageDosage">
                  <el-input v-model="formData.usageDosage" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="注意事项" prop="lookOut">
                  <el-input v-model="formData.lookOut" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="不良反应" prop="adverseReaction">
                  <el-input v-model="formData.adverseReaction" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div  slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
            <el-button type="primary" @click="handleUpdateMedicine">确定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 添加标签弹层 -->
      <div class="add-form">
        <el-dialog title="添加信息" :visible.sync="addDialogFormVisible" :modal="false">
          <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" status-icon label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="药名" prop="name">
                  <el-input v-model="formData.name"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成分" prop="ingredient">
                  <el-input v-model="formData.ingredient"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
<!--              <el-col :span="12">-->
<!--                <el-form-item label="成分" prop="ingredient">-->
<!--                  <el-input v-model="formData.ingredient"/>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
              <el-col :span="12">
                <el-form-item label="适应症" prop="indication">
                  <el-input v-model="formData.indication"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="用法用量" prop="usageDosage">
                  <el-input v-model="formData.usageDosage"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="禁忌" prop="taboo">
                  <el-input v-model="formData.taboo"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="分类" prop="category">
                  <el-select v-model="formData.category" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                    <!-- 注意：el-option 设置了 value 属性 -->
                    <el-option v-for="categoryOption in categoryOptions" :key="categoryOption" :label="categoryOption" :value="categoryOption"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <div class="custom-upload-container">
                  <div class="upload-title">图片上传</div>
                  <el-upload
                    class="avatar-uploader"
                    :action="baseUrl + '/image/userImage'"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :file-list="fileList"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="不良反应" prop="adverseReaction">
                  <el-input v-model="formData.adverseReaction"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注意事项" prop="lookOut">
                  <el-input v-model="formData.lookOut"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="药物相互作用" prop="drugInteraction">
                  <el-input v-model="formData.drugInteraction"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="ATC编码" prop="atcCode">
                  <el-input v-model="formData.atcCode"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="规格/包装" prop="specification">
                  <el-input v-model="formData.specification" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="规格/包装" prop="chineseMedicineName">
                  <el-input v-model="formData.plantMorphology" type="textarea" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div  slot="footer" class="dialog-footer">
            <el-button @click="addDialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddMedicine">确定</el-button>
          </div>
        </el-dialog>
        <!--导入表格-->
        <el-dialog
          :visible.sync="dialogVisibleExcel"
          width="40%"
          :modal="false"
          style="overflow: hidden"
          :before-close="handleClose">
          <div style="overflow: auto;width: auto;height: auto">
<!--action="http://127.0.0.1:8888/WMedicine/uploadExcel"-->
            <el-upload
              drag
              ref="upload"
              class="upload-demo"
              name="medicineExcel"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :on-success="handleSuccess"
              :file-list="fileList"
              :action="baseUrl + '/WMedicine/uploadExcel'"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传excel文件</div>
            </el-upload>
          </div>
          <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleExcel = false">取 消</el-button>
          <el-button type="primary" @click="batchMedicineExcelList">确定上传</el-button>
        </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import zhCn from 'element-ui/lib/locale/lang/zh-CN'
import { medicine } from '@/api/medicine'
import request from '@/api/request'

export default {
  data () {
    return {
      dialogVisibleExcel: false,
      dialogFormVisible4Edit: false,
      addDialogFormVisible: false,
      locale: zhCn,
      tableData: [],
      deleteButton: false,
      searchForm: {
        entrydate: null
      },
      fileList: [],
      baseUrl: '',
      imageUrl: '',
      formData: {
        imageUrl: ''
      },
      medicineExcel: null,
      categoryOptions: [],
      page: {
        total: 7,
        currentPage: 1,
        pageSize: 5,
        queryString: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        specification: [
          { required: true, message: '请输入规格', trigger: 'blur' }
        ],
        plantMorphology: [
          { required: true, message: '请输入中文名', trigger: 'blur' }
        ],
        adverseReaction: [
          { required: true, message: '请输入不良反应', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getData()
    this.getVMedicineCategory()
    this.promisesion()
    this.baseUrl = this.$requestcode.defaults.baseURL
  },
  methods: {
    getVMedicineCategory () {
      const token = localStorage.getItem('token')
      request.get('/tcCategoryMedicine/vmMedicine', {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + token
        }
      }).then(resp => {
        if (resp.data.flag === true) {
          this.categoryOptions = resp.data.data.map(item => item.category)
        }
      }).catch(err => {
        this.handleAxiosError(err)
      })
    },
    async getData () {
      const classData = {
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize,
        queryString: this.page.queryString
      }
      try {
        // 发送请求获取分页数据
        await medicine(classData).then(resp => {
          const data = resp.data
          this.page.total = data.total
          this.tableData = data.rows
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    promisesion () {
      request.get('/req/request', {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + localStorage.getItem('token')
        }
      }).then(resp => {
        // alert(resp.data.flag === true)
        if (resp.data.flag === true) {
          this.deleteButton = true
        } else {
          this.deleteButton = false
        }
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    // 模板下载
    downloadTemplate () {
      window.location.href = 'https://liuexcel.oss-cn-beijing.aliyuncs.com/medincine_template.xlsx'
    },
    onSubmit () {
      this.getData()
    },
    handleUpdate (row) {
      const token = localStorage.getItem('token')
      // alert(token)
      this.dialogFormVisible4Edit = true
      request.get('/wMedicine/' + row.id, {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + token
        }
      }).then(resp => {
        if (resp.data.flag === true) {
          this.formData = resp.data.data
          this.getData()
        }
      }).catch(err => {
        this.handleAxiosError(err)
      })
    },
    handleUpdateMedicine () {
      const token = localStorage.getItem('token')
      this.$refs.dataEditForm.validate((valid) => {
        if (valid) {
          request.put('/wMedicine/update', this.formData, {
            headers: {
              accept: 'application/json',
              Authorization: 'Bearer ' + token
            }
          }).then(resp => {
            if (resp.data.flag === true) {
              this.$message({
                type: 'success',
                message: resp.data.message
              })
              // this.fileList = []
              this.imageUrl = ''
              // this.$refs.editeUpload.submit()
              this.dialogFormVisible4Edit = false
              this.getData()
            }
          }).catch(err => {
            this.handleAxiosError(err)
          })
        }
      })
    },
    handleAddBtn () {
      this.addDialogFormVisible = true
      this.formData = {}
    },
    handleAddMedicine () {
      const token = localStorage.getItem('token')
      this.$refs.dataEditForm.validate((valid) => {
        if (valid) {
          request.post('/wMedicine/addMedicine', this.formData, {
            headers: {
              accept: 'application/json',
              Authorization: 'Bearer ' + token
            }
          }).then(resp => {
            if (resp.data.flag === true) {
              this.$message({
                type: 'success',
                message: resp.data.message
              })
              this.fileList = []
              this.imageUrl = ''
              // this.$refs.addUpload.submit()
              this.addDialogFormVisible = false
              this.getData()
            }
          }).catch(err => {
            this.handleAxiosError(err)
          })
        }
      })
    },
    refreshUn () {
      this.page.queryString = ''
      this.getData()
    },
    handleSelectionChange () {},
    deleteItem (row) {
      const token = localStorage.getItem('token')
      request.delete('/wMedicine/delete/' + row.id, {
        headers: {
          accept: 'application/json',
          Authorization: 'Bearer ' + token
        }
      }).then(res => {
        if (res.data.flag === true) {
          this.$message({
            type: 'success',
            message: res.data.message
          })
          this.getData()
        }
      }).catch(err => {
        this.handleAxiosError(err)
      })
    },
    // 批量导入
    batchMedicineExcelList () {
      this.$refs.upload.submit()
      this.dialogVisibleExcel = false
    },
    beforeUpload (file) {
      if (file === null) {
        this.$message.error('请选择文件')
        return false
      }
      const isXLS = file.type === 'application/vnd.ms-excel'
      if (isXLS) {
        return true
      }
      const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (isXLSX) {
        return true
      }
      this.$message.error('上传文件只能是xls或者xlsx格式!')
      return false
    },
    handleSuccess (resp, file) {
      // alert(JSON.stringify(resp))
      if (resp.flag === true) {
        this.$message({
          type: 'success',
          message: resp.message,
          offset: 80
        })
        this.getData()
        this.dialogVisible = false
        this.fileList = []
      } else {
        this.$message.error({
          message: resp.message,
          type: 'error',
          offset: 80
        })
      }
    },
    handlePageSizeChange (pageSize) {
      this.page.pageSize = pageSize
      // this.page.currentPage = 1 // 重置为第一页
      this.getData()
    },
    handleCurrentPageChange (currentPage) {
      this.page.currentPage = currentPage
      this.getData()
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.formData.imageUrl = res.data
      this.fileList = []
    },
    beforeAvatarUpload (file) {
      const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'] // 允许的文件格式

      const isAllowedFormat = allowedFormats.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isAllowedFormat) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isAllowedFormat && isLt2M
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.fileList = []
        })
        .catch(_ => {})
    },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader-icon {
  font-size: 25px;
  color: #2667c4;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #bcbebf;
  margin: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.custom-upload-container {
  display: flex;
  align-items: center;
  margin-left: 25px;
}

.upload-title {
  margin-left: 10px;
  white-space: nowrap;
}
.box-card {
  height: 2%;
}
.boxMain {
  margin-right: 70%;
  vertical-align: middle;
  white-space: nowrap;
}
</style>
